#!/usr/bin/env python
# coding: utf-8


from wcferry import Wcf

from textual.app import App, ComposeResult
from textual.widgets import Header, Log, Input, Button, Static
from textual.events import Key

from wcwidth import wcswidth

import time

def wc_rjust(text, length, padding=' '):
    return padding * max(0, (length - wcswidth(text))) + text

def format_message(sender, content):
    return time.strftime('%Y-%m-%d %H:%M:%S.') + "{:0>3}".format(str(int(time.time()*1000%1000))) + f" [{wc_rjust(sender, 50)}] - "+ content

def handle_message():
    try:
        msg = wcf.get_msg(block=False)
    except:
        return
    # if msg.sender != wx_id:
    #     continue

    if msg.type not in {1, 3, 34, 47, 66, 9999, 10000, 10002, 822083633, 922746929}:
        return

    if msg.from_group():
        # 群消息
        groupname = wcf.get_info_by_wxid(msg.roomid)['name']
        sender_name = wcf.get_alias_in_chatroom(msg.sender, msg.roomid)
        possible_friend = wcf.get_info_by_wxid(msg.sender)['remark']
        sender = groupname + '->' + (sender_name if not possible_friend else possible_friend)
    elif msg.from_self():
        sender = '自己'
    else:
        print(wcf.get_info_by_wxid(msg.sender))
        sender_info = wcf.get_info_by_wxid(msg.sender)
        sender = sender_info['name'] if len(sender_info['remark']) else sender_info['remark']

    # 自定义筛选
    if exclusively:
        if msg.from_group() and msg.roomid != wx_id:
            return
        if not msg.from_group() and msg.sender != wx_id:
            return

    if msg.type == 3:
        content = wcf.get_ocr_result(msg.extra)
    else:
        content = msg.content

    return format_message(sender, content)


class MessageHistory(Log):
    def add_mesasge(self, msg) -> None:
        self.write_line(msg)

    def on_mount(self) ->None:
        """Event handler called when widget is added to the app."""
        self.check_message()
        self.update_timer = self.set_interval(0.1, self.check_message, pause=True)
        self.update_timer.resume()

    def check_message(self) -> None:
        msg = handle_message()
        if not msg:
            return
        self.add_mesasge(msg)

class ChatEdit(Static):
    def compose(self) -> ComposeResult:
        yield Input(id='msg', type='text')
        yield Button('发送', id='send')       

class WeChatShadowClient(App):
    BINDINGS = [
        ('q', 'quit1', "Quit"),
        ('ctrl+s', 'send', 'Send')
    ]
    CSS_PATH = "ui.tcss"

    def on_mount(self) -> None:
        self.title = "touch touch fish"

    def compose(self) -> ComposeResult:
        yield Header()
        yield MessageHistory(id='msgLog')
        yield ChatEdit()
        #yield Footer()
        self.dark = True

    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Event handler called when a button is pressed."""
        button_id = event.button.id
        if button_id == 'send':
            self.action_send()

    def on_key(self, event: Key):
        if event.name == 'enter':
            self.action_send()


    def action_send(self) -> None:
        input = self.query_one("#msg")
        print(input.value)
        if not input.value:
            return
        wcf.send_text(input.value, wx_id)
        history = self.query_one(MessageHistory)
        history.add_mesasge(format_message(f'self -> {name}',input.value))
        input.value = ""

    def action_quit1(self) -> None:
        wcf.cleanup()
        self.action_quit()


wcf = Wcf()

msg_types = wcf.get_msg_types()

contacts = wcf.get_contacts()

exclusively = False


if __name__ == "__main__":
    print(wcf.get_msg_types())
    name = input("请输入消息发送到的聊天名:")
    ans = input("需要将接收限制到这个聊天吗?Empty for No")
    if ans and ans != 'No':
        exclusively = True

    for contact in contacts:
        if contact['name'] == name:
            wx_id = contact['wxid']
    if not wx_id:
        print('没有这个聊天')
        exit(-1)

    print('开始监听' + wx_id)
    
    if not wcf.is_login():
        print('wechat is not running.')
        exit(-1)
    if not wcf.is_receiving_msg():
        wcf.enable_receiving_msg()

    app = WeChatShadowClient()
    app.run()